﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using AtletIS.Shared.Entities;
using System.Data;
using System.Text.RegularExpressions;

namespace AtletIS.Shared.Helpers
{
    public static class PrintHelper
    {
        private static ResultCodesTableAdapter taResultCodes = new ResultCodesTableAdapter();

        public static void PrintRowHeader(StreamWriter sw, int rank)
        {
            if (rank % 2 == 1)
                sw.WriteLine(" <tr>");
            else
                sw.WriteLine(" <tr bgcolor=\"#CFECEC\">");
        }

        #region Name

        /// <summary>
        ///  Vráti meno
        /// </summary>
        public static string PrintName(string firstName, string surname)
        {
            return string.Format("{0} {1}", surname.ToUpper(), firstName);
        }

        /// <summary>
        ///  Vráti meno
        /// </summary>
        public static string PrintName(DataRow dr)
        {
            string firstName = dr["FirstName"].ToString();
            string surname = dr["Surname"].ToString();
            
            return string.Format("{0} {1}", surname.ToUpper(), firstName);
        }

        /// <summary>
        ///  Vráti meno štafety
        /// </summary>
        public static string PrintRelayName(DataRow dr, bool bClubCountry)
        {
            string clubId = dr["Club"].ToString();
            string clubName = dr["ClubName"].ToString();
            string countryId = dr["CountryId"].ToString();
            string countryName = dr["CountryName"].ToString();

            string surname = dr["Surname"].ToString();

            if (bClubCountry == true)
            {
                if (clubName != string.Empty)
                    return string.Format("{0} \"{1}\"", clubName, surname);
                else
                    return string.Format("{0} \"{1}\"", clubId, surname);
            }
            else
            {
                if (countryName != string.Empty)
                    return string.Format("{0} \"{1}\"", countryName, surname);
                else
                    return string.Format("{0} \"{1}\"", countryId, surname);
            }
        }

        #endregion

        public static string PrintFlagImage(DataRow dr)
        { 
            string countryId = dr["CountryId"].ToString();
            return string.Format("<img src=\"..\\Images\\Flags\\16px\\{0}.png\" height=\"16px\">", countryId);
        }

        #region ClubCountry

        /// <summary>
        ///  Vráti klub alebo krajinu
        /// </summary>
        public static string PrintClubCountry(bool bClubCountry, string clubId, string clubName, string countryId, string countryName)
        {
            if (bClubCountry == true)
            {
                if (clubName != string.Empty)
                    return clubName;
                else
                    return clubId;
            }
            else
            {
                if (countryName != string.Empty)
                    return countryName;
                else
                    return countryId;
            }
        }

        /// <summary>
        ///  Vráti klub alebo krajinu
        /// </summary>
        public static string PrintClubCountry(bool bClubCountry, DataRow dr)
        {
            string clubId = dr["Club"].ToString();
            string clubName = dr["ClubName"].ToString();
            string countryId = dr["CountryId"].ToString();
            string countryName = dr["CountryName"].ToString();

            if (bClubCountry == true)
            {
                if (clubName != string.Empty)
                    return clubName;
                else
                    return clubId;
            }
            else
            {
                if (countryName != string.Empty)
                    return countryName;
                else
                    return countryId;
            }
        }

        #endregion

        /// <summary>
        ///  Vráti výsledok
        /// </summary>
        public static string PrintResult(string result, int disciplineCode)
        {
            string strResult;

            if (result == "0")
                return string.Empty;

            switch (disciplineCode)
            { 
                case Globals.SprintCode:
                case Globals.LongRunCode:
                    strResult = result.PadLeft(8, '0');
                    strResult = strResult.Substring(0, 2) + ":" + strResult.Substring(2, 2) + ":" + strResult.Substring(4, 2) + "," + strResult.Substring(6, 2);
                    strResult = strResult.TrimStart('0', ':');
                    return strResult;

                case Globals.ThrowsCode: 
                case Globals.HorJumpCode:
                    if (result == "x" | result == "-")
                        strResult = result;
                    else
                    {
                        strResult = result.PadLeft(4, '0');
                        strResult = strResult.Substring(0, 2) + "," + strResult.Substring(2, 2);
                        strResult = strResult.TrimStart('0');
                    }
                    return strResult;
                
                case Globals.VerJumpCode:
                    return result;

                case Globals.MarathonCode:
                    result = RoundSecondsUp(result);
                    strResult = result.PadLeft(8, '0');
                    strResult = strResult.Substring(0, 2) + ":" + strResult.Substring(2, 2) + ":" + strResult.Substring(4, 2);
                    strResult = strResult.TrimStart('0', ':');
                    return strResult;

                default:
                    return string.Empty;
            }
        }

        /// <summary>
        /// Prevedie výkon na text.
        /// </summary>
        public static string PrintResult2(object result, int resultCode)
        {
            var timePrefixToReplace = new Regex(Regex.Escape("00:"));
            string resultOut = string.Empty;

            switch (resultCode)
            {
                // 1 = Čas v stotinách
                case 1:
                    if (result != null && result is DateTime)
                    {
                        var dt = Convert.ToDateTime(result);
                        resultOut = string.Format("{0:00}:{1:00}:{2:00},{3:00}", dt.Hour, dt.Minute, dt.Second, Math.Round(Convert.ToDecimal(dt.Millisecond / 10)));
                    }
                    if (result != null && result is TimeSpan)
                    {
                        var ts = (TimeSpan)result;
                        resultOut = string.Format("{0:00}:{1:00}:{2:00},{3:00}", ts.Hours, ts.Minutes, ts.Seconds, Math.Round(Convert.ToDecimal(ts.Milliseconds / 10)));
                    }
                    while (resultOut.StartsWith("00:"))
                        resultOut = timePrefixToReplace.Replace(resultOut, string.Empty, 1);
                    break;

                // 2 = Čas v desatinách
                case 2:
                    if (result != null && result is DateTime)
                    {
                        var dt = Convert.ToDateTime(result);
                        resultOut = string.Format("{0:00}:{1:00}:{2:00},{3:0}", dt.Hour, dt.Minute, dt.Second, Math.Round(Convert.ToDecimal(dt.Millisecond / 100)));
                    }
                    if (result != null && result is TimeSpan)
                    {
                        var ts = (TimeSpan)result;
                        resultOut = string.Format("{0:00}:{1:00}:{2:00},{3:0}", ts.Hours, ts.Minutes, ts.Seconds, Math.Round(Convert.ToDecimal(ts.Milliseconds / 100)));
                    }
                    while(resultOut.StartsWith("00:"))
                        resultOut = timePrefixToReplace.Replace(resultOut, string.Empty, 1);
                    break;
                
                // 3 = Čas v sekundách
                case 3:
                    if (result != null && result is DateTime)
                    {
                        var dt = Convert.ToDateTime(result);
                        if (dt.Millisecond > 0)
                            dt = dt.AddSeconds(1);

                        resultOut = string.Format("{0:00}:{1:00}:{2:00}", dt.Hour, dt.Minute, dt.Second);
                    }
                    else if (result != null && result is TimeSpan)
                    {
                        var ts = (TimeSpan)result;
                        if (ts.Milliseconds > 0)
                            ts = ts.Add(new TimeSpan(0, 0, 1));

                        resultOut = string.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds);
                    }
                    while (resultOut.StartsWith("00:"))
                        resultOut = timePrefixToReplace.Replace(resultOut, string.Empty, 1);
                    break;
            }

            return resultOut;
        }

        /// <summary>
        ///  Vráti výsledok alebo kód
        /// </summary>
        public static string PrintResultWithCode(int code, string result, DisciplineListEntity discipline)
        {
            if (code != 0)
            {
                return DatabaseHelper.GetResultCodesById(code).Rows[0]["Name"].ToString();
            }
            else
            {
                return PrintResult(result, discipline.DisciplineCode);
            }
        }

        /// <summary>
        ///  Vráti dátum narodenia
        /// </summary>
        public static string PrintBirthdate(DateTime birthDate)
        { 
            if (birthDate.Day == 1 & birthDate.Month == 1 & birthDate.Year == 1900)
                return string.Empty;

            if (birthDate.Day == 1 & birthDate.Month == 1)
                return birthDate.Year.ToString();

            return birthDate.ToString("dd.MM.yyyy");
        }

        /// <summary>
        ///  Vráti PB alebo SB
        /// </summary>
        public static string PrintPbSb(int disciplineCode, string resultQuality, int resultCode, int result, int pb, int sb)
        {
            if (resultCode != 0 | result == 0)
                return string.Empty;

            if (!string.IsNullOrEmpty(resultQuality))
                return resultQuality;

            switch (disciplineCode)
            {
                case 1:
                case 2:
                case 6:
                    if (pb > 100 & result < pb)
                    {
                        return "PB";
                    }
                    if (sb > 100 & result < sb)
                    {
                        return "SB";
                    }
                    break;

                case 3:
                case 4:
                case 5:
                    if (pb > 100 & result > pb)
                    {
                        return "PB";
                    }
                    if (sb > 100 & result > sb)
                    {
                        return "SB";
                    }
                    break;
            }

            return string.Empty;
        }

        public static string PrintPoints(DataRow dr)
        {
            try
            {
                if (Convert.ToDouble(dr["Points"]) > 0)
                    return Convert.ToDouble(dr["Points"]).ToString();
            }
            catch { }

            return string.Empty;
        }

        public static string PrintStartNumber(DataRow dr)
        {
            try
            {
                if (Convert.ToDouble(dr["StartNumber"]) > 0)
                    return "(" +  Convert.ToDouble(dr["StartNumber"]).ToString() + ")";
            }
            catch { }

            return string.Empty;
        }

        public static string PrintRank(DataRow dr)
        {
            try
            {
                if (Convert.ToDouble(dr["Rank"]) > 0)
                    return Convert.ToInt32(dr["Rank"]).ToString();
            }
            catch { }

            return string.Empty;
        }

        /// <summary>
        ///  Vráti čas zaokrúhlený na sekundy nahor
        /// </summary>
        private static string RoundSecondsUp(string sResult)
        {
            TimeSpan tsMarathonResult = TimeSpanHelper.FromDbResultString(sResult);

            if (tsMarathonResult.Milliseconds == 0)
            { 
                return string.Format("{0}{1:00}{2:00}00", tsMarathonResult.Hours, tsMarathonResult.Minutes, tsMarathonResult.Seconds);
            }
            else if (tsMarathonResult.Seconds == 59)
            {
                return string.Format("{0}{1:00}{2:00}00", tsMarathonResult.Hours, tsMarathonResult.Minutes + 1, 0);
            }
            else
            {
                return string.Format("{0}{1:00}{2:00}00", tsMarathonResult.Hours, tsMarathonResult.Minutes, tsMarathonResult.Seconds + 1);
            }

                
        }






    }
}
